import org.junit.jupiter.api.Test

/**
 * @Author ZhouHang
 * @Date 24/6/28 周五
 */

class Calculator {
    fun addIntArray() {
        var initialValue = 0;
        for (number in 1..5) {
            println(
                Thread.currentThread().name
                        + " ---> " + initialValue + " + "
                        + number + " = "
                    .plus(String.format("%d", (initialValue + number)))
            );
            initialValue += number;
            Thread.sleep(500);
        }
    }
}

class LockTest {
    @Test fun `Test Thread`() {
        val thread1 = Thread {
            while (true) {
                println("Hello")
                Thread.sleep(1000)
            }
        }

        val thread2 = Thread {
            while (true) {
                println("World")
                Thread.sleep(1000)
            }
        }

        thread1.start()
        thread2.start()
        thread1.join()
        thread2.join()
    }

    @Test fun `Calculate`() {
        val calculator = Calculator();

        val thread1 = Thread {
            calculator.addIntArray();
        }

        val thread2 = Thread {
            calculator.addIntArray();
        }

        thread1.start()
        thread2.start()
        thread1.join()
        thread2.join()
    }

    val calculator = Calculator();

    fun sumUsingSynchronization(): Unit = synchronized(calculator) {
        calculator.addIntArray();
    }

    @Test fun `Calculate With Lock`() {
        val thread1 = Thread {
            synchronized(calculator) {
                calculator.addIntArray();
            }
        }

        val thread2 = Thread {
            synchronized(calculator) {
                calculator.addIntArray();
            }
        }

        thread1.start()
        thread2.start()
        thread1.join()
        thread2.join()
    }
}